//
//  WBNetworkTool+OAuth.swift
//  WeiboTen
//
//  Created by ItHeiMa on 2017/7/7.
//  Copyright © 2017年 itHeima. All rights reserved.
//

import UIKit

extension WBNetworkTool {
    /// 计算属性，调用时临时创建
    var loginUrl: String {
        return "https://api.weibo.com/oauth2/authorize?client_id=\(appKey)&redirect_uri=\(redirectURI)"
    }
    
    /// 登录
    ///
    /// - Parameters:
    ///   - withCode: 新浪认证服务器在用户授权之后返回的code
    ///   - success: 完成回调，告诉调用者是否登录成功
    func login(withCode: String, success: @escaping (Bool)->()) {
        //1. 获取token
        requestToken(code: withCode, competetion: { (tokenInfo) in
            //如果成功获取到token
            if let tokenDic = tokenInfo as? [String: Any] {
                self.requestUserInfo(token: tokenDic["access_token"]!, uid: tokenDic["uid"]!, competetion: { (userInfo) in
                    //print(userInfo)
                    //代表成功获取到用户信息
                    if var userDic = userInfo as? [String: Any]  {
                        //字典的合并
                        for (k, v) in tokenDic {
                            userDic[k] = v
                        }
                        
                        //将token和用户信息成功保存之后，则登录成功
                        WBUserAccount.shared.save(dict: userDic)
                        //回调，告诉调用者登录成功了
                        success(true)
                        
                    } else {
                        //如果只获取到了token，但没有获取到用户信息，则也代表登录失败
                        success(false)
                    }
                })
            } else {
                //如果获取token失败，则代表登录失败
                success(false)
            }
        })
    }
    
    /// 获取accesstoken
    ///
    /// - Parameters:
    ///   - code: code
    ///   - competetion: 完成回调
    func requestToken(code: String, competetion: @escaping (Any?)->()) {
        let parameters = ["client_id": appKey, "client_secret": appSecret, "grant_type": "authorization_code", "code": code, "redirect_uri": redirectURI]
        
        let url = "https://api.weibo.com/oauth2/access_token"
        
        WBNetworkTool.shared.request(urlStr: url, method: "POST", parameters: parameters, callBack: { (responseObject) in
            competetion(responseObject)
        })
    }
    
    /// 获取用户信息
    ///
    /// - Parameters:
    ///   - token: access_token
    ///   - uid: 登录的用户的id
    ///   - competetion: 完成回调
    func requestUserInfo(token: Any, uid: Any,  competetion: @escaping (Any?)->()) {
        let parameters = ["uid": uid, "access_token":token]
        let url = "https://api.weibo.com/2/users/show.json"
        
        WBNetworkTool.shared.request(urlStr: url, method: "GET", parameters: parameters, callBack: { (responseObject) in
            competetion(responseObject)
        })
    }
}
